package com.snowleopard.common.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntUrlPathMatcher;
import org.springframework.security.web.util.UrlMatcher;

import com.snowleopard.findpeople.service.account.AuthorityService;

public class FilterInvocationSecurityMetadataSourceImpl implements
		FilterInvocationSecurityMetadataSource {
	private static final Logger log = Logger
			.getLogger(FilterInvocationSecurityMetadataSourceImpl.class);

	private UrlMatcher urlMatcher = new AntUrlPathMatcher();
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	@Autowired
	private AuthorityService authorityService;

	public FilterInvocationSecurityMetadataSourceImpl() {
	}

	public void loadResourceDefine() {
		try {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			// 从DB中查询得所有分配了权限(authority)的Resource和其对应的权限
			LinkedHashMap<String, String> resourceMapTemp = authorityService
					.getRequestMap();

			for (Iterator<String> keys = resourceMapTemp.keySet().iterator(); keys
					.hasNext();) {
				String url = keys.next();
				String[] authoritys = resourceMapTemp.get(url).split(",");

				Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

				for (String authority : authoritys) {
					ConfigAttribute ca = new SecurityConfig("ROLE_" + authority);
					atts.add(ca);
				}

				resourceMap.put(url, atts);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	// According to a URL, Find out permission configuration of this URL.
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		// guess object is a URL.
		String resquestURL = ((FilterInvocation) object).getRequestUrl();
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resourceURL = ite.next();
			if (urlMatcher.pathMatchesUrl(resourceURL, resquestURL)) {
				return resourceMap.get(resourceURL);
			}
		}
		return null;
	}

	public static void main(String[] args) {
		UrlMatcher urlMatcher = new AntUrlPathMatcher();
		System.out.println(urlMatcher.pathMatchesUrl("/account/user*",
				"/account/user.action"));
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

}
